import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { getCatList } from '../service/song';

interface IStatu {
  catList: any;
  currentCat: string;
}
const initialState: IStatu = {
  catList: {},
  currentCat: '',
};

export const fetchCatList = createAsyncThunk('songs/catList', async () => {
  const response: any = await getCatList();
  return response;
});

const songSlice = createSlice({
  initialState,
  name: 'songs',
  reducers: {
    setCurrentCat: (state, { payload }: PayloadAction<string>) => {
      state.currentCat = payload;
    },
    setCatList: (state, { payload }: PayloadAction<any>) => {
      state.catList = payload;
    },
  },
  extraReducers(builder) {
    // 获取分类列表
    // 处理请求开始状态
    builder.addCase(fetchCatList.pending, (state) => {
      // console.log('pending');
    });
    // 处理请求成功状态
    builder.addCase(fetchCatList.fulfilled, (state, action) => {
      const response = action.payload;
      const organizedData: any = {};
      // 初始化每个大分类为空数组
      Object.values(response.categories).forEach((category) => {
        organizedData[category as string] = [];
      });
      // 遍历小分类数组，将其归类到对应的大分类中
      response.sub.forEach((item: any) => {
        const categoryIndex = item.category;
        const categoryName = response.categories[categoryIndex];
        if (categoryName) {
          organizedData[categoryName].push(item);
        }
      });
      state.catList = organizedData;
    });
    // 处理请求失败状态
    builder.addCase(fetchCatList.rejected, (state, action) => {});
  },
});

export const songReducer = songSlice.reducer;

export const { setCurrentCat, setCatList } = songSlice.actions;
